package com.vic.fastjson;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONTokener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.*;

public abstract class Test {

	public static void main(String[] args) throws Exception {


//		String encode = URLEncoder.DEFAULT.encode(a, Charset.defaultCharset());
//		System.out.println(encode);

//		System.out.println(URLDecoder.decode(encode, Charset.defaultCharset()));


//		String aa = URLEncoder.encode(a, "utf-8");
//		System.out.println(aa);
//		System.out.println(URLDecoder.decode(aa, "utf-8"));

		// [{"quantity":1,"item_name":"xxxxxxx","ext_info":[{"ext_key":"image_material_id","ext_value":"2022022400502200000062568801"}]}]

		// 3 Map与json字符串
//		test3();

		// 2 数据与json字符串
//		test2();

		// 1 对象与json字符串
		test1();

	}

	private static void test3() {

		/**
		 * 将map转换为json字符串
		 */
		Map<String, String> map = new HashMap<String, String>();
		map.put("create_time", "2018-05-31 13:59:33");
		map.put("id", "1");
		map.put("name", "张三");
		String jsonStr = JSON.toJSONString(map);
//		System.out.println(jsonStr);


		// 方式1
		HashMap maps = JSON.parseObject(jsonStr, HashMap.class);
		System.out.println(maps.get("id"));
		System.out.println(maps.get("name"));
		System.out.println(maps.get("create_time"));

		// 方式1

//		PageResult<EventDto> eventDtoPageResult = JSON.parseObject(json, new TypeReference<PageResult<EventDto>>() {});
		Map<String, String> userMap = JSON.parseObject(jsonStr, new TypeReference<Map<String, String>>() {});
		System.out.println(userMap.get("id"));
		System.out.println(userMap.get("name"));
		System.out.println(userMap.get("create_time"));
	}

	private static void test2() {

		/**
		 * 6 集合转换为json对象
		 */
		List<User> userList = new ArrayList<User>();
		userList.add(new User(1, "u1"));
		userList.add(new User(2, "u2"));

//		System.out.println(JSON.toJSON(userList));

		/**
		 * 集合转换为json字符串
		 */
//		System.out.println(JSON.toJSONString(userList));

		/**
		 * 7 将json字符串数组 转换 为JSONArray对象
		 */
		String str = "[{\"id\":1,\"name\":\"u1\"},{\"id\":2,\"name\":\"u2\"}]";
		JSONArray parseArray = JSON.parseArray(str);
		System.out.println(parseArray.toJSONString());

		/**
		 * 将json字符串数组 转换 指定类型的集合
		 */
		List<User> uList = JSON.parseArray(str, User.class);
//		System.out.println(uList);

		/**
		 * 对象包含对象
		 */
		List<User> userList2 = new ArrayList<User>();
		userList2.add(new User(1, "u1"));
		userList2.add(new User(2, "u2"));

		Group group = new Group();
		group.setId(1);
		group.setName("g1");
		group.setUserList(userList2);

//		System.out.println(JSON.toJSONString(group));

		//{"id":1,"name":"g1","userList":[{"id":1,"name":"u1"},{"id":2,"name":"u2"}]}
		String groupStr = "{\"id\":1,\"name\":\"g1\",\"userList\":[{\"id\":1,\"name\":\"u1\"},{\"id\":2,\"name\":\"u2\"}]}";
		Group g = JSON.parseObject(groupStr, Group.class);
//		System.out.println(g);
//		System.out.println(g.getUserList());
	}

	private static void test1() throws Exception {

		User u1 = new User(1, "u1");

		/**
		 * 1 对象转换为json字符串
		 */
		String jsonString = JSON.toJSONString(u1);
//		System.out.println(jsonString);

		/**
		 * 2 对象转换为json对象
		 */
//		System.out.println(JSON.toJSON(u1));

		/**
		 * 3 json字符串转换为指定对象
		 */
		User user = JSON.parseObject(jsonString, User.class);
//		System.out.println(user);

		/**
		 * 4 将json字符串解析为JSONObject(key/value数据格式)
		 */
		JSONObject jsonObject = JSON.parseObject(jsonString);

		Integer id = jsonObject.getInteger("id");
		Integer id1 = (Integer)jsonObject.get("id");
//		System.out.println(id);
//		System.out.println(id1);

		/**
		 * 5 put操作
		 */
		jsonObject.put("age", 18);
		Integer age = jsonObject.getInteger("age");
//		System.out.println(age);


		String userJsonStr = "{\"name\":\"u2\",\"id\":2,\"bir\":\"2023-03-01\"}";
//		String userJsonStr = "{\"id\":1,\"name\":\"u1\"}";
		JSONObject userJsonObject = JSON.parseObject(userJsonStr);

//		System.out.println(userJsonObject);

//		String groupStr = "{\"job\":\"程序员\",\"addr\":\"shanghai\",\"id\":1,\"name\":\"g1\",\"userList\":[{\"id\":1,\"name\":\"u1\"},{\"name\":\"u2\",\"id\":2,\"bir\":\"2023-03-01\"}]}";
//		String groupStr = "{\"data\":[{\"bank_code\":\"中国银行\",\"card_no\":\"6214830217879807\",\"encrypt_fields\":[\"mobile_number\"],\"id_number\":\"34122319901125255X\",\"mobile_number\":\"EPd2oRaKyXtt+/SPn4Ji2HJHB5JqPDeav\",\"name\":\"罗利华\",\"out_user_id\":\"u_1\"}],\"timestamp\":1718950384181}";
//		String groupStr = "[{\"id\":1,\"name\":\"u1\"},{\"name\":\"u2\",\"id\":2,\"bir\":\"2023-03-01\"}]";
//		String groupStr = "[\"name\",\"u1\","bir\"]";
		String groupStr = "{\"data\":[{\"bank_code\":\"中国银行\",\"card_no\":\"6214830217879807\",\"encrypt_fields\":[\"mobile_number\"],\"id_number\":\"34122319901125255X\",\"mobile_number\":\"q8AfXeriI5i2eLSurZU1O4h3Ef1lSQe1j0ulI4bKM4H4oNJhYMiLQ9+i7Z2nAoj8hE+/IHZfDHP8PzeFw2dptYtFIAnK6M7Lr7xYonFpskMKxZrwH/xNPXyi3IL+bdHpDdXH7gOnkhkSaUnzeEohO1vG8L4ArkiaU15+yYDNARs=\",\"name\":\"罗利华\",\"out_user_id\":\"u_1\"}],\"timestamp\":1718956123554}";



		if(isJsonObject(groupStr)) {
			JSONObject jsonObj = JSON.parseObject(groupStr);
			JSONObject jsonObject1 = transSortJSONObject(jsonObj);
			System.out.println(jsonObject1.get("data"));
		} else if(isJsonArray(groupStr)) {
			JSONArray jsonArr = JSON.parseArray(groupStr);
			JSONArray jsonArr1 = transSortJSONArray(jsonArr);
			System.out.println(jsonArr1);
		} else {

		}



		/*ObjectMapper objectMapper = new ObjectMapper();
		JsonNode jsonNode = objectMapper.readTree(groupStr);
		if (jsonNode.isObject()) {
			JSONObject jsonObj = JSON.parseObject(groupStr);
			JSONObject jsonObject1 = transSortJSONObject(jsonObj);
			System.out.println(jsonObject1);
		}
		if (jsonNode.isArray()) {
			JSONArray jsonArr = JSON.parseArray(groupStr);
			JSONArray jsonArr1 = transSortJSONArray(jsonArr);
			System.out.println(jsonArr1);
		}*/

//		String dataStr = jsonObject.getJSONObject(DATA) == null ? null : JSON.toJSONString(jsonObject.getJSONObject(DATA), SerializerFeature.MapSortField);

		// 对象包含：对象、数据
		// 数据包含：包装类型、对象
	}

	private static boolean isJsonArray(String str) {
		JSONTokener jsonTokener = new JSONTokener(str, JSONConfig.create());
		if(jsonTokener.nextClean() == '[') {
			return true;
		}
		return false;
	}

	private static boolean isJsonObject(String str) {
		JSONTokener jsonTokener = new JSONTokener(str, JSONConfig.create());
		if(jsonTokener.nextClean() == '{') {
			return true;
		}
		return false;
	}


	public static JSONObject transSortJSONObject(JSONObject rawObj) {
		JSONObject sortedJsonObj = new JSONObject(true);
		rawObj.keySet().stream().sorted().forEachOrdered(key -> {

			Object valueObj = rawObj.get(key);

			if(ObjectUtil.isNull(valueObj)) {
				sortedJsonObj.put(key, valueObj);
			} else {
				if (isJsonObject(valueObj.toString())) {
					JSONObject valJsonObj = JSON.parseObject(valueObj.toString());
					JSONObject transSortJsonObject = transSortJSONObject(valJsonObj);
					sortedJsonObj.put(key, transSortJsonObject);
				} else if (isJsonArray(valueObj.toString())) {
					JSONArray valJsonArr = JSON.parseArray(valueObj.toString());
					JSONArray transSortJsonArr = transSortJSONArray(valJsonArr);
					sortedJsonObj.put(key, transSortJsonArr);
				} else {
					sortedJsonObj.put(key, valueObj);
				}
			}
		});
		return sortedJsonObj;
	}

	public static JSONArray transSortJSONArray(JSONArray rawArr) {
		JSONArray sortedJsonArr = new JSONArray();
		for (Object valueObj : rawArr) {
			if(ObjectUtil.isNull(valueObj)) {
				sortedJsonArr.add(valueObj);
				continue;
			}
			if (isJsonObject(valueObj.toString())) {
				JSONObject valJsonObj = JSON.parseObject(valueObj.toString());
				JSONObject transSortJsonObject = transSortJSONObject(valJsonObj);
				sortedJsonArr.add(transSortJsonObject);
			} else if (isJsonArray(valueObj.toString())) {
				JSONArray valJsonArr = JSON.parseArray(valueObj.toString());
				JSONArray transSortJsonArr = transSortJSONArray(valJsonArr);
				sortedJsonArr.add(transSortJsonArr);
			} else {
				sortedJsonArr.add(valueObj);
			}
		}
		return sortedJsonArr;
	}

}
